package com.taikang.hmp.hbusiness.diabetes.measure.job.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.service.impl.BaseServiceImpl;
import com.taikang.hmp.frame.common.tools.DateTimeUtils;
import com.taikang.hmp.frame.customer.bean.CustomerInfo;
import com.taikang.hmp.frame.user.bean.AuthUserInfo;
import com.taikang.hmp.hbusiness.diabetes.measure.medicine.bean.Medplan;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.bean.MedcineType;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.bean.Sugar;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.bean.SugarMonitor;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.bean.SugarPlan;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.service.ISugarService;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.service.SugarUtil;

/** 
 * 血糖监测
 * author:qrp
 * time:2015年8月24日 下午1:58:13
 */
public class SugarMonitorAutoJobServiceImpl extends BaseServiceImpl implements ISugarMonitorAutoJobService{
	
	private static Logger logger = LoggerFactory.getLogger(SugarMonitorAutoJobServiceImpl.class);
	
	private ISugarService sugarService;
	
	public ISugarService getSugarService() {
		return sugarService;
	}

	public void setSugarService(ISugarService sugarService) {
		this.sugarService = sugarService;
	}



	/**
	 * 保存初始血糖计划
	 */
	public void saveInitSugarPlan(String customerId) {
		CustomerInfo customerInfo = (CustomerInfo)super.getNewDao().queryForObject("user_space.getCustomer_id", customerId);
		
		//客户的用药计划
		Map<String, String> map0 = new HashMap<String, String>();
		map0.put("customerid" , customerId);
		map0.put("end_date"   , DateTimeUtils.getCurrentDate());
		//将所获得的药物类型转换成0-2（非用药/口服药；胰岛素（非预混型）；胰岛素（预混型）2）的形式
		String type = "0";
		List<MedcineType> planMedTypes = null;
		Medplan medplan = (Medplan)super.getNewDao().queryForObject("medicine_space.getMedicinePlanByCustomer", map0);
		if(medplan==null){
			logger.info("InitSugarPlan:customerId:"+customerId+"未制定用药计划");
			//return;
		}else{
		
		//
		String med_plan_id = medplan.getPlan_id();
		planMedTypes = super.getNewDao().queryForList("medicine_space.getMedcineTypeOfPlan", med_plan_id);
		
		//将所获得的药物类型转换成0-2（非用药/口服药；胰岛素（非预混型）；胰岛素（预混型）2）的形式
		// type = SugarUtil.convertMedcineType(planMedTypes.get(0).getType());
		}
		
		//初始血糖计划
		String sugarPlanCode = "";
		if(planMedTypes!=null){
		for(int i=0;i<planMedTypes.size();i++){
			String temptype = SugarUtil.convertMedcineType(planMedTypes.get(i).getType());
			if(Integer.parseInt(temptype)>Integer.parseInt(type)){
				type = temptype;
			}
			
		}
		}
			//糖化血红蛋白
			String param1 = "0";
			if(customerInfo.getHemoglobin() != null){
				param1 = customerInfo.getHemoglobin();
			}
			//血糖值
			String param2 = "0";
			if(customerInfo.getSugar() != null){
				param2 = customerInfo.getSugar();
			}
			//餐后血糖值
			String param3 = "0";
			if(customerInfo.getSugarafter() != null){
				param3 = customerInfo.getSugarafter();
			}
			
			if(StringUtils.isNoneEmpty(param1) && StringUtils.isNoneEmpty(param2) && StringUtils.isNoneEmpty(param3)){
				//取得初始血糖计划
				sugarPlanCode = SugarUtil.designInitSugarPlan(Float.parseFloat(param1), Float.parseFloat(param2), Float.parseFloat(param3), type);
			}
		
		
		
		//
		if(StringUtils.isEmpty(sugarPlanCode)){
			logger.info("InitSugarPlan:customerid["+customerId+"]血糖计划编码设计为空！");
		}else{
			logger.info("InitSugarPlan:customerid["+customerId+"]血糖计划编码推导结论："+sugarPlanCode);
		}
		
		
		//获取监测方案
		List<SugarMonitor> sugarMonitorList = SugarUtil.convertToSugarPlans(sugarPlanCode);
		for (int j = 0; j < sugarMonitorList.size(); j++) {
			//每周执行7次
			if(sugarMonitorList.get(j).getTime() == 7){
				for (int k = 0; k < 7; k++) {
					int temp = k+1 - SugarUtil.getWeekOfDate(new Date());
					SugarPlan sugarPlan = new SugarPlan();
					String plan_id = java.util.UUID.randomUUID().toString();
					sugarPlan = sugarMonitorList.get(j).getSugarPlan();
					sugarPlan.setPlan_id(plan_id);
					sugarPlan.setDate(DateTimeUtils.formatDate(SugarUtil.getDateAfter(new Date(), temp)));
					sugarPlan.setCustomer_id(customerId);
					sugarPlan.setSource_cd(customerInfo.getSource_cd());
					sugarPlan.setOperater(customerInfo.getOperater());
					sugarService.insertOrUpdateSugarPlan(sugarPlan);
				}
			}
			//每两周执行1次
			else if(sugarMonitorList.get(j).getTime() == 14){
				SugarPlan sugarPlan = new SugarPlan();
				String plan_id = java.util.UUID.randomUUID().toString();
				sugarPlan = sugarMonitorList.get(j).getSugarPlan();
				sugarPlan.setPlan_id(plan_id);
				sugarPlan.setDate(DateTimeUtils.formatDate(SugarUtil.getDateAfter(new Date(), 14)));
				sugarPlan.setCustomer_id(customerId);
				sugarPlan.setSource_cd(customerInfo.getSource_cd());
				sugarPlan.setOperater(customerInfo.getOperater());
				sugarService.insertOrUpdateSugarPlan(sugarPlan);
			}
			//每周执行1次
			else{
				//if( sugarMonitorList.get(j).getTime() >= SugarUtil.getWeekOfDate(new Date()) ){
					SugarPlan sugarPlan = new SugarPlan();
					String plan_id = java.util.UUID.randomUUID().toString();
					int temp = sugarMonitorList.get(j).getTime() - SugarUtil.getWeekOfDate(new Date());
					sugarPlan = sugarMonitorList.get(j).getSugarPlan();
					sugarPlan.setPlan_id(plan_id);
					sugarPlan.setDate(DateTimeUtils.formatDate(SugarUtil.getDateAfter(new Date(), temp)));
					sugarPlan.setCustomer_id(customerId);
					sugarPlan.setSource_cd(customerInfo.getSource_cd());
					sugarPlan.setOperater(customerInfo.getOperater());
					sugarService.insertOrUpdateSugarPlan(sugarPlan);
				//}
			}
		}
	}
	
	
	
	/**
	 * 取得自己的血糖计划编码
	 */
	public String designSugarPlanCode(String customerId) {
		String result = null;
		String today      = DateTimeUtils.getCurrentDate();
		String twoWeekAgo = DateTimeUtils.formatDate(SugarUtil.getDateBefore(new Date(), 14));
		//将所获得的药物类型转换成0-2（非用药/口服药；胰岛素（非预混型）；胰岛素（预混型）2）的形式
		String type ="0";
		//用药计划中的药品种类
		List<MedcineType> medTypeOfPlan=null;
		//获取客户测量计划
		int bplancount = 0;//餐前计划测量数
		int aplancount = 0;//餐后计划测量数
		Dto paramDto = new BaseDto();
		paramDto.put("customerid", customerId);
		paramDto.put("startdate", twoWeekAgo);
		paramDto.put("enddate", today);
		List<Dto> planList = sugarService.getSugarPlan(paramDto);
		if(planList!=null){
			for(int i=0;i<planList.size();i++){
				Dto tresult = planList.get(i);
				if("1".equals(tresult.getAsString("breakfastpre"))){
					bplancount = bplancount+1;
				}
				if("1".equals(tresult.getAsString("lunchpre"))){
					bplancount = bplancount+1;
				}
				if("1".equals(tresult.getAsString("dinnerpre"))){
					bplancount = bplancount+1;
				}
				if("1".equals(tresult.getAsString("breakfastaft"))){
					aplancount = aplancount+1;
				}
				if("1".equals(tresult.getAsString("lunchaft"))){
					aplancount = aplancount+1;
				}
				if("1".equals(tresult.getAsString("dinneraft"))){
					aplancount = aplancount+1;
				}
				if("1".equals(tresult.getAsString("sleeppre"))){
					aplancount = aplancount+1;
				}
				
			}
			
		}
		//客户的用药计划
		Map<String, String> map0 = new HashMap<String, String>();
		map0.put("customerid" , customerId);
		map0.put("end_date"   , today);
		Medplan medplan = (Medplan)super.getNewDao().queryForObject("medicine_space.getMedicinePlanByCustomer", map0);
		if(medplan==null){
			logger.info("customerId:"+customerId+"未制定用药计划");
			//return null;
		}else{
		
		//用药计划中的药品种类
		medTypeOfPlan = super.getNewDao().queryForList("medicine_space.getMedcineTypeOfPlan", medplan.getPlan_id());
		}
		
		if(medTypeOfPlan!=null){
			for(int i=0;i<medTypeOfPlan.size();i++){
				//将所获得的药物类型转换成0-2（非用药/口服药；胰岛素（非预混型）；胰岛素（预混型）2）的形式
				String temptype = SugarUtil.convertMedcineType(medTypeOfPlan.get(i).getType());
				if(Integer.parseInt(temptype)>Integer.parseInt(type)){
					type = temptype;
				}
				
			}
			}
		
		
		
		//用药计划改变，看两周用药情况
		//if(medPlanList.size() == 1){
		if(medplan!=null && DateTimeUtils.isInDateRange(medplan.getDate(), twoWeekAgo , today)){	
			if(type.equals("0")){
				result = "1#2";
			}else if(type.equals("1")){
				result = "0#3";
			}else if(type.equals("2")){
				result = "0#4";
			}
			logger.info("customerId:"+customerId+"用药计划日期"+medplan.getDate()+"在"+twoWeekAgo+"~"+today+"之内:"+result);
		}
		//用药计划没变，看两周血糖情况
		//else if(medPlanList.size() > 1){
		else{
			map0.put("end_date"   , today+" 23:59");
			map0.put("start_date" , twoWeekAgo+" 00:00");
			List<Sugar>  sugarList = super.getNewDao().queryForList("sugar_space.getSugarList", map0);
			List<String> list =  new ArrayList<String>();
			List<String> list1 = new ArrayList<String>();
			List<String> list2 = new ArrayList<String>();
			for(int i = 0;i<sugarList.size();i++){
				list.add(sugarList.get(i).getValue());
				//判断是餐前还是餐后
				if(SugarUtil.getB_A(sugarList.get(i).getTimespan_cd()) == 0){
					list1.add(sugarList.get(i).getValue());
				}else{
					list2.add(sugarList.get(i).getValue());
				}
			}
			//
			if (type.equals("0")) {
				// 服用口服药
				int sugarResult = SugarUtil.getResult(list);
				if (sugarResult != 0) {
					if (sugarResult == 1) {
						result = "1#1";
					} else if (sugarResult == 2) {
						result = "1#1";
					} else if (sugarResult == 3) {
						result = "1#2";
					}
				} else if (SugarUtil.getResult1(list1, list2,bplancount,aplancount) != 0) {
					result = "1#3";
				} else {
					result = "1#2";
				}
			} else if(type.equals("1")){
				//胰岛素为非预混型
				int sugarResult = SugarUtil.getResult(list);
				if (sugarResult != 0) {
					if (sugarResult == 1) {
						result = "0#1";
					} else if (sugarResult == 2) {
						result = "0#1";
					} else if (sugarResult == 3) {
						result = "0#3";
					}
				} else if (SugarUtil.getResult1(list1, list2,bplancount,aplancount) != 0) {
					result = "0#5";
				} else {
					result = "0#3";
				}
			}else if(type.equals("2")){
				//胰岛素为预混型
				int sugarResult = SugarUtil.getResult(list);
				if (sugarResult != 0) {
					if (sugarResult == 1) {
						result = "0#1";
					} else if (sugarResult == 2) {
						result = "0#1";
					} else if (sugarResult == 3) {
						result = "0#4";
					}
				} else if (SugarUtil.getResult1(list1, list2,bplancount,aplancount) != 0) {
					result = "0#6";
				} else {
					result = "0#4";
				}
			}
			//logger.info("customerId:"+customerId+"用药计划日期"+medplan.getDate()+"在"+twoWeekAgo+"~"+today+"之外:"+result);
		}
		System.out.println("更改计划："+customerId+" 为："+result);
		return result;
	}

	
	/**
	 * 获取所有注册用户信息
	 */
	public List<AuthUserInfo> getAllUserInfo() {
		return super.getNewDao().queryForList("user_space.getAllUser");
	}

	
	/**
	 * 查找customer中is_init_plan不是1的
	 */
	public boolean isNotInitPlan(String customerid) {
		Integer count = (Integer)super.getNewDao().queryForObject("user_space.countNotInitPlan", customerid);
		if(count > 0){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 更新状态信息
	 */
	public void updateInitPlanStatus(String customerId,String status) {
		try {
			Dto paramDto = new BaseDto();
			paramDto.put("customer_id",customerId);
			paramDto.put("is_init_plan",status);
			super.getNewDao().update("user_space.update_initplan", paramDto);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断是否胰岛素治疗
	 */
	public boolean is_check(String customer_id) {
		Map<String, String> map0 = new HashMap<String, String>();
		map0.put("customerid" , customer_id);
		//map0.put("start_date" , DateTimeUtils.formatDate(SugarUtil.getDateBefore(new Date(), 14)));
		map0.put("end_date"   , DateTimeUtils.getCurrentDate());
		Medplan medplaninfo = (Medplan)super.getNewDao().queryForObject("medicine_space.getMedicinePlanByCustomer", map0);
		String type = "";
		if(medplaninfo!=null){
			List<MedcineType> infoDetail = super.getNewDao().queryForList("medicine_space.getMedcineTypeOfPlan", medplaninfo.getPlan_id());
			//将所获得的药物类型转换成0-2（非用药/口服药；胰岛素（非预混型）；胰岛素（预混型）2）的形式
			type = SugarUtil.convertMedcineType(infoDetail.get(0).getType());
		}
		if(type.equals("1") || type.equals("2")){
			return true;
		}
		return false;
	}
}
